package com.duk.main;


import java.util.ArrayList;
import java.util.HashMap;

import com.duk.util.DataBaseUtil;
import com.duk.util.WebImageBuilder;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class FavoriteActivity extends Activity implements OnClickListener{


	private static final int SELECT_NULL = 1;
	TextView edit;
	ListView listView;
	private ArrayList<HashMap<String,String>> arrayList = new ArrayList<HashMap<String,String>>();
	
	private boolean editFlag;
	private MyBaseAdapter myBaseAdapter;
	private Handler handler;
	
	public FavoriteActivity()
	{
		this.editFlag = false;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.favorite_view);
		
	    listView = (ListView)findViewById(R.id.news_listview);
		edit = (TextView)findViewById(R.id.edit_layout);
		//设置编辑事件
		edit.setOnClickListener(this);
		this.myBaseAdapter = new MyBaseAdapter(this);
		
		handler = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				switch(msg.what){
				case SELECT_NULL:
					//没有收藏时
					findViewById(R.id.relative).setVisibility(8);
					listView.setVisibility(8);
					findViewById(R.id.LinearLayout01).setBackgroundResource(R.drawable.not_fav);
					openDialog();
					break;
				default:
					break;
				}
				myBaseAdapter.notifyDataSetChanged();
			}	
		};
		new PrepData().start();
		
		
		listView.setAdapter(myBaseAdapter);
		//设置条目的事件
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				String newsType = arrayList.get(position).get("news_id");
				//判断时候是类别的分隔 arrayList
				if(!newsType.equals("category")){
					Intent itemintent = new Intent(FavoriteActivity.this,ActivityShowDescription.class);
			    	 Bundle b = new Bundle();
			    	 b.putString("title", arrayList.get(position).get("title"));
			    	 b.putString("news_type", arrayList.get(position).get("news_type"));
			    	 b.putString("description", arrayList.get(position).get("webdata"));
			    	 b.putString("link", arrayList.get(position).get("url"));
			    	 b.putString("pubdate", arrayList.get(position).get("pubdate"));
			    	 b.putString("content", arrayList.get(position).get("content"));
			    	 b.putSerializable("image_path", arrayList.get(position).get("image_path"));
			    	 itemintent.putExtra("android.intent.extra.rssItem", b);
			         startActivityForResult(itemintent, 0);
				} 
				
			}
		});
	}

	//数据初始化的线程
	class PrepData extends Thread{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			//从数据库取出所有数据
			Message msg = new Message();
			DataBaseUtil localDataBaseUtil = new DataBaseUtil(FavoriteActivity.this);
			localDataBaseUtil.open();

			ArrayList<HashMap<String,String>> localArrayList = localDataBaseUtil.selectAllData();
			
			//没有数据
			if((localArrayList == null) || (localArrayList.size() <= 0)){
				msg.what = SELECT_NULL;
			} else {
				 arrayList = localArrayList;
			}
			//关闭数据库
		    localDataBaseUtil.closeDataBase();
		    handler.sendMessage(msg);
		}
		
	}
	
	
	
	//删除某一条新闻删除记录的线程
	class ItemDelete extends Thread{

		String newsId;
		
		ItemDelete(String news_id){
			this.newsId = news_id;
		}
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			//从数据库删除这条记录 news_id
			DataBaseUtil localDataBaseUtil1 = new DataBaseUtil(FavoriteActivity.this);
		    localDataBaseUtil1.open();			
			localDataBaseUtil1.deleteByNewsId(newsId);
			localDataBaseUtil1.closeDataBase();
			new PrepData().start();
		}
		
	}

	//打开对话框 
	private void openDialog()
	{
	  AlertDialog.Builder builder = new AlertDialog.Builder(this);
	  builder.setTitle("收藏");
	  builder.setMessage("收藏夹没有文章");
	  builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
		
		@Override
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			
		}
	  });
	  Dialog dialog = builder.create();
	  dialog.show();
	}
	
	//编辑和取消时间
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.edit_layout:
			if(editFlag){
				edit.setText("编辑");
				editFlag = false;
				this.myBaseAdapter.notifyDataSetChanged();
			} else {
				edit.setText("取消");
				editFlag = true;
				this.myBaseAdapter.notifyDataSetChanged();
			}
			break;
		case R.id.back_iamge1:
			break;
		}
	}
	

	//设置适配器
	class MyBaseAdapter extends BaseAdapter
	{

		private Context context;
		
		
		MyBaseAdapter(Context context)
		{
			this.context = context;
		}
		
		//取得对象标识的类别字符名称
		private String getNewsType(String paramString)
		{
			int i = Integer.valueOf(paramString);
			String str = null;
			switch (i){
			case 0:
				str = FavoriteActivity.this.getString(R.string.china);
				break;
			case 1:
		        str = FavoriteActivity.this.getString(R.string.international);
		        break;
			case 2:
		        str = FavoriteActivity.this.getString(R.string.house);
		        break;
			case 3:
		        str = FavoriteActivity.this.getString(R.string.sports);
		        break;
			case 4:
		        str = FavoriteActivity.this.getString(R.string.cultural);  
		        break;
			case 5:
		        str = FavoriteActivity.this.getString(R.string.cars);
		        break;
			case 6:
		        str = FavoriteActivity.this.getString(R.string.yunnan);
		        break;
		    default:
		        str = FavoriteActivity.this.getString(R.string.china);
		        break;
			}
			return str;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return FavoriteActivity.this.arrayList.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return Integer.valueOf(position).intValue();
		}

		
		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			//当前条目标识
			if (FavoriteActivity.this.arrayList == null){
				return convertView;
			}
			//取得相关控件
			View view = View.inflate(FavoriteActivity.this,R.layout.favorite_item,null);
			ImageView delete = (ImageView)view.findViewById(R.id.delete);
			ImageView itemImage = (ImageView)view.findViewById(R.id.news_item_image);
			TextView title = (TextView)view.findViewById(R.id.news_item_title);
			TextView content = (TextView)view.findViewById(R.id.news_item_content);
			ImageView rightFlag = (ImageView)view.findViewById(R.id.right_flag);

			//判断是否是类别分隔arrayList
			String category = arrayList.get(position).get("news_id");
			if (category.equals("category")){	
				//类别显示
				view.setBackgroundResource(R.drawable.grey_box);
				//这个布局先失效
				view.setEnabled(false);
				String type = getNewsType(arrayList.get(position).get("news_type"));
				title.setText(type);
				ViewGroup.LayoutParams layoutParmas = title.getLayoutParams();
				layoutParmas.width = ViewGroup.LayoutParams.FILL_PARENT;
				layoutParmas.height = 25;
				title.setLayoutParams(layoutParmas);
				title.setGravity(16);
				title.setTextSize(15.0F);
				title.setTextColor(R.color.fav_text_item);
				itemImage.setVisibility(8);
				content.setVisibility(8);
				rightFlag.setVisibility(8);
			} else {
				//条目显示
				rightFlag.setVisibility(0);
				delete.setVisibility(8);
				setViewImage(itemImage, arrayList.get(position).get("image_path"));
			    title.setText(arrayList.get(position).get("title"));
			    content.setText(arrayList.get(position).get("webdata"));			    
			   //编辑判断
				if (FavoriteActivity.this.editFlag){
					rightFlag.setVisibility(8);
					delete.setVisibility(0);
					delete.setTag(position);
					delete.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {
							String news_id = arrayList.get(Integer.parseInt(v.getTag().toString())).get("news_id");
							new ItemDelete(news_id).start();
						}
					});
				} else {
					rightFlag.setVisibility(0);
					delete.setVisibility(8);
				}   
			}
			return view;	
		}	
			
	}
	
	@Override
	public void onOptionsMenuClosed(Menu menu) {
		// TODO Auto-generated method stub
		super.onOptionsMenuClosed(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}
	
	
	 public void setViewImage(final ImageView v, String url) {
	    	//如果只是单纯的把图片显示，而不进行缓存。直接用下面的方法拿到URL的Bitmap就行显示就OK  
	       Bitmap bitmap = WebImageBuilder.returnBitMap(url);  
	       ((ImageView) v).setImageBitmap(bitmap);  
//	         imageLoader.loadDrawable(url, new AsyncImageLoader.ImageCallback() {
//	             public void imageLoaded(Drawable imageDrawable, String imageUrl) {
//	                 if(imageDrawable!=null && imageDrawable.getIntrinsicWidth()>0 ) {
//	                     v.setImageDrawable(imageDrawable);
//	                 }
//	             }
//	         });
	     }
	
	 
	 
	 //退出提示对话框
	 private Dialog ExitDialog(Context context) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(R.drawable.icon);
			builder.setTitle("生活新报提示");
			builder.setMessage("确定退出么?");
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							finish();
						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

						}
					});
			return builder.create();
		}
	   
	    //返回提示退出
	    @Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				ExitDialog(FavoriteActivity.this).show();
				return true;
			}
			return super.onKeyDown(keyCode, event);
		}
	 
	 
	   //单击相应的新闻后返回触发的事件，刷新数据
	    protected void onActivityResult(int requestCode, int resultCode,
	             Intent data) {
	         new PrepData().start();
	     }
	    
}











